package cn.ldj.ztomcat.servlets;


import cn.hutool.core.util.ReflectUtil;
import cn.ldj.ztomcat.catalina.Context;
import cn.ldj.ztomcat.http.MyRequest;
import cn.ldj.ztomcat.http.MyResponse;
import cn.ldj.ztomcat.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class InvokerServlet extends HttpServlet {
    private static InvokerServlet instance = new InvokerServlet();


    public static synchronized InvokerServlet getInstance() {
        return instance;
    }

    private InvokerServlet() {

    }

    public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws IOException, ServletException {
        MyRequest request = (MyRequest) httpServletRequest;
        MyResponse response = (MyResponse) httpServletResponse;

        String uri = request.getUri();
        Context context = request.getContext();
        String servletClassName = context.getServletClassName(uri);

//        Object servletObject = ReflectUtil.newInstance(servletClassName);
//        ReflectUtil.invoke(servletObject, "service", request, response);
//
//        response.setStatus(Constant.CODE_200);
        try {
            Class servletClass = context.getWebappClassLoader().loadClass(servletClassName);
            Method[] methods = servletClass.getMethods();
            System.out.println("成功获取到class对象，方法数目=" + methods.length);
            //成功获取到class对象=23
            //修改class后增加了一个方法，输出的还是23个方法。
            //成功获取到class对象=23
            //重启之后，再来是24个方法了。为什么？
            //成功获取到class对象=24
            System.out.println("servletClass:" + servletClass);
            System.out.println("servletClass'classLoader:" + servletClass.getClassLoader());
//            Object servletObject = ReflectUtil.newInstance(servletClass);
            Object servletObject = context.getServlet(servletClass);
            System.out.println("成功获取到访问的servlet对象=" + servletObject);
            //对象不一样，为什么执行的方法的结果是一样的？class没有更新？
            //成功获取到访问的servlet对象=cn.ldj.test.HelloServlet@453ab3c9
            //成功获取到访问的servlet对象=cn.ldj.test.HelloServlet@4e729046
            //成功获取到访问的servlet对象=cn.ldj.test.HelloServlet@73bc42e9
            ReflectUtil.invoke(servletObject, "service", request, response);
            response.setStatus(Constant.CODE_200);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
